<?php

namespace App\Http\Controllers;

use App\Models\SmsVerify;

/**
 * 验证码控制器
 *
 * @package App\Http\Controllers
 */
class CptController extends Controller
{

	/**
	 * 生成验证码
	 *
	 * @author lxp 20170105
	 * @return mixed
	 */
	public function show()
	{
		return app('captcha')->show();
	}

	/**
	 * 检查验证码
	 *
	 * @author lxp 20170105
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function check()
	{
		return response()->json(app('captcha')->check(request('captcha')));
	}

	/**
	 * 发送短信验证码
	 *
	 * @author lxp
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function send_sms()
	{
		$this->validate(request(), [
			'phone' => 'required|mobile',
			'captcha' => 'captcha'
		]);

		// 可添加针对手机号或IP的验证
		$lastVerify = SmsVerify::where('mobile', request('phone'))->where('status', 1)->orderBy('created_at', 'DESC')->first();
		if ($lastVerify && (date('U') - strtotime($lastVerify->created_at)) < 60) {
			return response()->json([
				'message' => "操作过于频繁，请稍候再试",
				'errors' => [
					'captcha' => '操作过于频繁，请稍候再试'
				]
			], 422);
		}

		// 将该手机号之前的验证码都置为失效
		SmsVerify::where('mobile', request('phone'))->where('status', 1)->update(['status' => 3]);

		// 生成手机验证码并保存
		$smsObj = new SmsVerify();
		$smsObj->mobile = request('phone');
		$smsObj->smscode = rand(100000, 999999);
		$smsObj->ip = client_real_ip();
		$smsObj->plat = request('p', 'w');
		$smsObj->save();
		// 发送短信
		$smsObj->sendSmsNotification();

		return response_json();
	}
}
